package com.smashit.tacocloud.repository.impl;

import com.smashit.tacocloud.domain.Ingredient;
import com.smashit.tacocloud.domain.Taco;
import com.smashit.tacocloud.repository.TacoRepository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jinshan_jiang
 * @version 1.0
 * @since 2024/4/9
 */
@Repository
public class JdbcTacoRepository implements TacoRepository {
    private JdbcTemplate jdbcTemplate;
    private SimpleJdbcInsert tacoInsert;

    public JdbcTacoRepository(JdbcTemplate jdbcTemplate) {
        tacoInsert = new SimpleJdbcInsert(jdbcTemplate)
                .withTableName("taco")
                .usingGeneratedKeyColumns("id");
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public Taco findOne(Long id) {
        return null;
    }

    @Override
    public Taco save(Taco taco) {
        long tacoId = saveTacoInfo(taco);
        taco.setId(tacoId);
        for (Ingredient ingredient : taco.getIngredients()) {
            saveIngredientToTaco(ingredient, tacoId);
        }
        return taco;
    }

    private void saveIngredientToTaco(Ingredient ingredient, long tacoId) {
        jdbcTemplate.update("insert into taco_ingredients (taco, ingredient) values (?,?)", tacoId, ingredient.getId());
    }

    private long saveTacoInfo(Taco taco) {
        taco.setCreatedAt(new Date());
        // PreparedStatementCreator psc = new PreparedStatementCreatorFactory("insert into taco (name, createdAt) values (?,?)", Types.VARCHAR, Types.TIMESTAMP)
        //         .newPreparedStatementCreator(Arrays.asList(taco.getName(), new Timestamp(taco.getCreatedAt().getTime())));
        Map<String, Object> values = new HashMap<>();
        values.put("name", taco.getName());
        values.put("createdAt", taco.getCreatedAt());
        // KeyHolder keyHolder = new GeneratedKeyHolder();

        // jdbcTemplate.update(psc, keyHolder);
        return tacoInsert.executeAndReturnKeyHolder(values).getKey().longValue();
    }
}
